<template>
	<div class="allcontainer" style="position: relative;">
		<div class="h2">活动修改</div>
		<div class="main bg-white" >
			<a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" @submit="handleSubmit">
				<a-form-item label="学生组织/班级">
					<a-input disabled v-show="false" v-decorator="['ClubID']" />
					<a-input disabled v-show="false" v-decorator="['ClassID']" />
					<a-input disabled v-show="form.getFieldValue('ClubName')" v-decorator="['ClubName']" />
					<a-input disabled v-show="form.getFieldValue('ClassName')" v-decorator="['ClassName']" />
				</a-form-item>
				<a-form-item label="活动类型">
					<a-input disabled v-show="false" v-decorator="['TypeID']" />
					<a-input disabled v-decorator="['TypeName']" />
				</a-form-item>
				<a-form-item label="活动标题" v-show="form.getFieldValue('TypeItemID')">
					<a-input disabled v-show="false" v-decorator="['TypeItemID']" />
					<a-input disabled v-decorator="['TypeItemName']" />
				</a-form-item>
				<a-form-item label="活动标题" v-show="!form.getFieldValue('TypeItemName')"><a-input v-decorator="['Title', { rules: [{ required: !form.getFieldValue('TypeItemName')?true:false, message: '活动标题不能为空' }] }]" /></a-form-item>
				<a-form-item label="活动时长（h）" v-if="IsHour"><a-input type="number" v-decorator="['HourNum', { rules: [{ required: true, message: '请输入活动时间' }] }]" /></a-form-item>
				<a-form-item label="是否需要报名" v-show="clubShow">
					<a-radio-group @change="IsNeedApplyChange" v-decorator="['IsNeedApply', { rules: [{ required: clubShow?true:false, message: '请选择是否需要报名' }] }]">
						<a-radio :value="true">是</a-radio>
						<a-radio :value="false">否</a-radio>
					</a-radio-group>
					<oprateBtn class="tishi" icon="icon-wenhao" color="green" title="如是，参加活动必须先报名，然后签到；如为否，不需要提前报名加入，活动现场扫码即可"></oprateBtn>
				</a-form-item>
				<a-form-item label="诚信值" v-show="form.getFieldValue('ClubID')">
					<a-input-number :min="0" :max="100" style="width: 100%;" placeholder="请输入诚信值" v-decorator="['HonestyScore', { rules: [{ required: form.getFieldValue('ClubID'), message: '请输入诚信值' }, { validator: intValidator }] }]" />
				</a-form-item>
				<a-form-item label="是否需要提交作业" v-show="clubShow">
					<a-radio-group  v-decorator="['IsNeedActivityJob', { rules: [{ required: clubShow?true:false, message: '请选择是否需要提交作业' }],initialValue:false }]">
						<a-radio :value="true">是</a-radio>
						<a-radio :value="false">否</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item label="报名时间" v-show="form.getFieldValue('IsNeedApply') && clubShow">
					<a-range-picker show-time v-decorator="['ApplyTime', { rules: [{ required: form.getFieldValue('IsNeedApply') && clubShow?true:false, message: '报名时间不能为空' }] }]" />
				</a-form-item>
				<a-form-item label="参加活动是否需要审批" v-show="form.getFieldValue('IsNeedApply') && clubShow">
					<a-radio-group v-decorator="['ApplyIsNeedExam', { rules: [{ required: form.getFieldValue('IsNeedApply') && clubShow?true:false, message: '请选择参加活动是否需要审批' }] }]">
						<a-radio :value="true">是</a-radio>
						<a-radio :value="false">否</a-radio>
					</a-radio-group>
					<oprateBtn class="tishi" icon="icon-wenhao" color="green" title="如是，申请加入活动人员必须审批通过才可加入；如为否，申请加入活动人员申请后无需审批直接加入"></oprateBtn>
				</a-form-item>
				<a-form-item label="是否设置奖项" v-show="clubShow">
					<a-radio-group v-decorator="['IsHasPrize', { rules: [{ required: clubShow?true:false, message: '请选择是否设置奖项' }] }]">
						<a-radio :value="true">是</a-radio>
						<a-radio :value="false">否</a-radio>
					</a-radio-group>
					<oprateBtn class="tishi" icon="icon-wenhao" color="green" title="如果选择设置奖项，则需在申请完结之前添加奖项，否则无法提交完结申请"></oprateBtn>
				</a-form-item>
				<a-form-item label="活动时间">
					<a-range-picker show-time v-decorator="['activityDate', { rules: [{ required: true, message: '活动时间不能为空' }] }]" />
				</a-form-item>
				<a-form-item label="场地管理" v-show="clubShow">
					<a-input @click="venueReserveDataFun" v-decorator="['venueReserveData']" />
					<div v-for="(item, i) in venueList" class="flex venueli">
						<div>{{ item.VenueName }} -- {{ item.Date }} -- {{ item.VenueTimeTable }}</div>
						<i @click="deleteVenue(i)" class="el-icon-circle-close" style="position: relative;top: 13px;left: 5px;"></i>
					</div>
				</a-form-item>
				<a-form-item label="活动人数" v-show="clubShow">
					<a-select
						:allowClear="true"
						placeholder="全部"
						optionFilterProp="children"
						showSearch
						style="width:100px;margin-right:20px;"
						@change="PeopleNumFun"
						v-model="PeopleNumIf"
					>
						<a-select-option v-for="(item, index) in PeopleNumList" :key="index" :value="item.Key">{{ item.Value }}</a-select-option>
					</a-select>
					<a-input
						v-show="PeopleNumIf == 1"
						style="width:100px;"
						type="number"
						v-decorator="['PeopleNum', { rules: [{ required: true, message: '活动人数不能为空' }, { validator: allintValidator }] }]"
					/>
					<!-- <span style="color:#f00;margin-left:10px;">填写-1代表不限制</span> -->
				</a-form-item>
				<a-form-item v-for="item in data" :label="item.Name">
					<a-input
						v-if="item.FieldType == 1"
						v-decorator="[
							item.ID,
							{ rules: [{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' }, { validator: rules[item.ID] ? rules[item.ID].validator : '' }] }
						]"
					/>
					<a-input
						v-if="item.FieldType == 2"
						type="textarea"
						:auto-size="global.textareaHeight"
						v-decorator="[
							item.ID,
							{ rules: [{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' }, { validator: rules[item.ID] ? rules[item.ID].validator : '' }] }
						]"
					/>
					<a-input
						v-if="item.FieldType == 3"
						type="number"
						v-decorator="[
							item.ID,
							{
								rules: [
									{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' },
									{ validator: rules[item.ID] ? rules[item.ID].validator : intValidator }
								]
							}
						]"
					/>
					<a-input
						v-if="item.FieldType == 4"
						type="number"
						:step="0.01"
						v-decorator="[
							item.ID,
							{ rules: [{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' }, { validator: rules[item.ID] ? rules[item.ID].validator : '' }] }
						]"
					/>
					<!-- {{ JSON.stringify(rules) }} -->
					<a-upload
						v-if="item.FieldType == 5 || item.FieldType == 6"
						v-decorator="[item.ID, { rules: [{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' }] }]"
						:accept="item.FieldType == 5 ? '' : 'image/*'"
						:action="requestUrl + '/Common/DoUploadFile?type=file'"
						list-type="picture-card"
						:file-list="fileList[item.ID]"
						@preview="handlePreview"
						:before-upload="e => beforeUploadfile(e,item.ID)"
						@change="e => handleChange(e, item.ID)"
					>
						<div>
							<a-icon type="plus" />
							<div class="ant-upload-text">Upload</div>
						</div>
					</a-upload>
					<a-date-picker
						v-if="item.FieldType == 7"
						@change="e => dataChange(e, item.ID, 'data')"
						v-decorator="[item.ID, { rules: [{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' }] }]"
					/>
					<a-time-picker
						v-if="item.FieldType == 8"
						@change="e => dataChange(e, item.ID, 'time')"
						v-decorator="[item.ID, { rules: [{ required: item.IsMust, message: item.ErroeMsg ? item.ErroeMsg : item.Name + '不能为空' }] }]"
					/>
				</a-form-item>
				<a-form-item class="fixed-bottom" style="float: right;margin-right: 50px;">
					<a-button type="primary" html-type="submit">提交</a-button>
				</a-form-item>
				
			</a-form>
		</div>
		<!-- <div class="main-apply">
			<div class="h3">审批信息</div>
			<a-steps class="apply-con" progress-dot v-if="flowData.length>0" :current="1" direction="vertical">
				<a-step v-for="(item, index) in flowData" :title="item.FlowTypeName+(item.IsAdopt?'通过':'驳回')" :description="item.AddTime" />
			</a-steps>
			<div v-if="flowData.length==0" class="nothing">暂无审批信息</div>
		</div> -->
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel"><img alt="example" style="width: 100%" :src="previewImage" /></a-modal>
	<venue class="venue" @closevenue="closevenue" v-if="venueIf"></venue>
	</div>
</template>

<script>
import moment from 'moment';
import Func from '@/utils/func';
import venue from '@/components/venue.vue';
import { UserActivityDetail, UserUpdateActivity, UserDoGetActivityTypeList } from '@/api/follow';
const data = [];
export default {
	components: {
		venue
	},
	data() {
		return {
			detail: {},
			layoutContentHeight: window.innerHeight - 268 + 'px',
			icofileList: [],
			fileList: {},
			previewVisible: false,
			previewImage: '',
			fileList1: [],
			previewVisible1: false,
			previewImage1: '',
			ActivityTypeList: [],
			data,
			flowData: [],
			applyIf: false,
			formLayout: 'horizontal',
			form: this.$form.createForm(this, {
				name: 'coordinated'
			}),
			formValue: {},
			dataValue: {},
			time: moment(),
			rules: {
				// validator: (rule, val, callback) => {
				// 			// var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
				// 			let pattern = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/;
				// 			if (!pattern.test(val)) {
				// 				callback('请输入正确手机号');
				// 			} else {
				// 				callback();
				// 			}
				// 			callback();
				// 		}
			},
			text: {},
			requestUrl: this.global.requestUrl,
			PeopleNumList: this.global.PeopleNumList,
			PeopleNumIf: 1,
			IsHour: true,
			clubShow:true,
			venueIf: false,
			venueList: [],
		};
	},
	computed: {},
	created() {
		this.getList();
	},
	mounted() {},
	methods: {
		closevenue(data) {
			this.venueIf = false
			console.log(data)
			if (data.length > 0) {
				this.venueList = this.venueList.concat(data)
				let obj = {}
				let productArr = this.venueList.reduce((cur, next) => {
					obj[next.TimeTableID] ? '' : (obj[next.TimeTableID] = true && cur.push(next))
					return cur
				}, []) // 设置cur默认类型为数组，并且初始值为空的数组
				this.venueList = productArr
				const res = new Map();
				this.venueList = this.venueList.filter((item) => !res.has(item['VenueTimeTableID']) && res.set(item['VenueTimeTableID'], 1));
			}
		
		},
		deleteVenue(i) {
			this.venueList.splice(i, 1)
		},
		venueReserveDataFun() {
			console.log(1)
			this.venueIf = true
		},
		moment,
		IsNeedApplyChange(e){
			if(!e.target.value){
				this.form.setFieldsValue({ ApplyIsNeedExam: false });
			}
		},
		allintValidator(rule, value, callback) {
			let pattern = /(^-?[1-9]\d*$)/;
			if (value && !pattern.test(value)) {
				callback('请输入整数');
			} else {
				callback();
			}
			callback();
		},
		intValidator(rule, value, callback) {
			let pattern = /(^[1-9]\d*$)/;
			if (value && !pattern.test(value)) {
				callback('请输入正整数');
			} else {
				callback();
			}
			callback();
		},
		applyHander() {
			// let item={id:this.$route.query.ID}
			this.text = {
				ID: this.$route.query.ID
			};
			this.applyIf = true;
		},
		PeopleNumFun(e) {
			if (e) {
				this.PeopleNumIf = e;
				this.form.setFieldsValue({
					PeopleNum: e == 1 ? '' : -1
				});
			}
		},
		async getList() {
			let that = this;
			let data = {};
			let res2 = await UserDoGetActivityTypeList(data);
			this.ActivityTypeList = res2.data.data;
			data.id = this.$route.query.ID;
			let res = await UserActivityDetail(data);
			this.detail = res.data.data;
			this.data = res.data.formData;
			this.flowData = res.data.flowData;
			this.venueList = res.data.resultVenueReserveData||[];
			this.form.setFieldsValue({
				ClubID:res.data.data.ClubID,
				ClubName:res.data.data.ClubName,
				ClassID:res.data.data.ClassID,
				ClassName:res.data.data.ClassName,
				TypeItemID:res.data.data.TypeItemID,
				Title: res.data.data.Title,
				TypeID: res.data.data.TypeID,
				TypeName: res.data.data.TypeName,
				TypeItemName:res.data.data.TypeItemName,
				activityDate:[res.data.data.StartTime,res.data.data.EndTime],
				ApplyTime:[res.data.data.ApplyStartTime,res.data.data.ApplyEndTime],
				Ico: res.data.data.Ico,
				PeopleNum: res.data.data.PeopleNum,
				ApplyIsNeedExam: res.data.data.ApplyIsNeedExam,
				IsHasPrize: res.data.data.IsHasPrize,
				HourNum: res.data.data.HourNum,
				IsNeedApply:res.data.data.IsNeedApply,
				HonestyScore:res.data.data.HonestyScore,
				IsNeedActivityJob:res.data.data.IsNeedActivityJob,
				venueList:res.data.resultVenueReserveData
			});
			this.icofileList = res.data.data.Ico
				? [
						{
							uid: 0,
							name: res.data.data.Ico.split('|')[0],
							status: 'done',
							url: this.requestUrl + res.data.data.Ico.split('|')[1]
						}
				  ]
				: [];
			setTimeout(function() {
				if (that.detail.PeopleNum == -1) {
					that.PeopleNumIf = 2;
				} else {
					that.PeopleNumIf = 1;
				}
				if (that.detail.HourNum > 0) {
					that.IsHour = true;
				} else {
					that.IsHour = false;
				}
				that.clubShow = that.detail.ClubName?true:false
				let list = res.data.formData;
				for (var i = 0; i < list.length; i++) {
					if (list[i].FieldType == 8) {
						that.form.setFieldsValue({
							[list[i].ID]: list[i].Value.indexOf('2020-10-10')>-1?list[i].Value:'2020-10-10 ' + list[i].Value
						});
					} else {
						that.form.setFieldsValue({
							[list[i].ID]: list[i].Value
						});
					}
					if (list[i].FieldType == 5 || list[i].FieldType == 6) {
						// that.fileList = Object.assign(that.fileList, {
						// 	[list[i].ID]: []
						// });
						that.fileList = { ...that.fileList, [list[i].ID]: [] };
					}
				}
				for (let i in that.fileList) {
					for (let n = 0; n < list.length; n++) {
						if (list[n].ID == i) {
							let arr = list[n].Value.split(',');
							for (let m = 0; m < arr.length; m++) {
								if (arr[m]) {
									that.fileList[i].push({ uid: m, url: that.requestUrl + arr[m].split('|')[1], name: arr[m].split('|')[0], status: 'done' });
								}
							}
						}
					}
				}
			}, 200);
		},
		closeFunction(data) {
			this.$emit('closeFun', data);
		},
		closeFun() {
			this.applyIf = false;
		},
		handleCancel() {
			this.previewVisible = false;
			this.previewImage = '';
		},
		async handlePreview(file) {
			if (file.url) {
				this.previewImage = file.url;
			} else {
				this.previewImage = this.requestUrl + file.response.url;
			}
			window.open(this.previewImage, '_blank')
		},
		icohandleChange({ fileList }, name) {
			this.icofileList = fileList;
		},
		beforeUploadfile(file,name){
			const isLt10M = file.size / 1024 / 1024 < 10;
			if (!isLt10M) {
				this.fileList[name] = this.fileList[name].splice(this.fileList[name].length-1,1)
				this.$message.error('文件大小不能超过10M!');
			}
			return isLt10M;
		},
		handleChange(info, name) {
			if(!info.file.status){
				return false
			}
			let { fileList } = info;
			const status = info.file.status;
			if (status === 'done') {
				if(info.file.response.code==0){
					this.$message.success(info.file.response.msg)
					this.fileList[name] = [...fileList]; //重点
				}else{
					this.$message.error(info.file.response.msg)
					this.fileList[name] = this.fileList[name].splice(this.fileList[name].length-1,1)
				}
			}
			this.fileList[name] = [...fileList]; //重点
		},
		// handleChange({ fileList }, name) {
		// 	this.fileList[name] = fileList;
		// },
		dataChange(e, name, type) {
			if (type == 'data') {
				let time = moment(e).format('YYYY-MM-DD HH:mm:ss');
				this.dataValue = Object.assign(this.dataValue, { [name]: time });
			} else {
				let time = moment(e).format('HH:mm:ss');
				this.dataValue = Object.assign(this.dataValue, { [name]: time });
			}
		},
		handleSubmit(e) {
			e.preventDefault();
			this.form.validateFields(async (err, values) => {
				if (!err) {
					let data = values;
					data.ID = this.detail.ID;
					data.ClubID = this.detail.ClubID;
					let arr1 = [];
					for (let m = 0; m < this.icofileList.length; m++) {
						if (this.icofileList[m].url) {
							if (this.icofileList[m].url.indexOf(this.requestUrl) > -1) {
								this.icofileList[m].url = this.icofileList[m].url.substring(this.requestUrl.length);
							}
							arr1.push(this.icofileList[m].name + '|' + this.icofileList[m].url);
						} else {
							arr1.push(this.icofileList[m].response.fileName + '|' + this.icofileList[m].response.url);
						}
					}
					data.Ico = arr1.join(',');
					for (let i in this.fileList) {
						let arr = [];
						for (let m = 0; m < this.fileList[i].length; m++) {
							if (this.fileList[i][m].url) {
								if (this.fileList[i][m].url.indexOf(this.requestUrl) > -1) {
									this.fileList[i][m].url = this.fileList[i][m].url.substring(this.requestUrl.length);
								}
								arr.push(this.fileList[i][m].name + '|' + this.fileList[i][m].url);
							} else {
								arr.push(this.fileList[i][m].response.fileName + '|' + this.fileList[i][m].response.url);
							}
						}
						data[i] = arr.join(',');
					}
					data = Object.assign(data, this.formValue, this.dataValue);
					if(data.activityDate){
						data.StartTime = moment(data.activityDate[0]).format('YYYY-MM-DD HH:mm:ss')
						data.EndTime = moment(data.activityDate[1]).format('YYYY-MM-DD HH:mm:ss')
					}
					if(data.ApplyTime){
						data.ApplyStartTime = moment(data.ApplyTime[0]).format('YYYY-MM-DD HH:mm:ss')
						data.ApplyEndTime = moment(data.ApplyTime[1]).format('YYYY-MM-DD HH:mm:ss')
					}
					data.venueReserveData = this.venueList
					let res = await UserUpdateActivity(data);
					if (res.data.code == 0) {
						this.$message.success(res.data.msg);
						this.$router.go(-1);
					}
				}
			});
		}
	}
};
</script>

<style lang="less" scoped>

.main-apply {
	width: 36%;
	float: right;

	.apply-con {
		margin-top: 20px;
	}

	.nothing {
		text-align: center;
		margin: 50px auto;
	}
}

.h3 {
	font-size: 14px;
	background: #f6f8f8;
	color: #1890ff;
	padding: 4px 10px;
}

.ant-calendar-picker,
.ant-time-picker{
	width: 100%!important;
}
</style>
